﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.IO;
using System.Data.SQLite;
using System.Diagnostics;


namespace LuZhouLaoJiao
{
    public partial class TestAcidity : Form
    {
        public TestAcidity()
        {
            InitializeComponent();
        }

        public DataTable dt = new DataTable();
        Boolean isRowAdded = false;
        //MySqlConnection conn = null;
        //MySqlCommand comm = null;
        //MySqlDataReader reader = null;

        SQLiteConnection conn = null;
        SQLiteCommand comm = null;
        SQLiteDataReader reader = null;

        string strCon = null;
//         string dbUser = Global.getRegeditValue("localDBUser");
//         string dbPwd = Global.getRegeditValue("localDBPwd");
//         string database = Global.getRegeditValue("localDatabase");
//         string ip = Global.getRegeditValue("localIP");
        string pici_id = null;
        int rowCount = 0;
        Timer dingshi = null;
        bool finish = false;
        int yangbenbianhao = 0;
        FileStream fs = null;
        StreamReader readFile = null;
        Process control = null;
        bool qidong = false;

        private void TestAcidity_Load(object sender, EventArgs e)
        {
            if (Global.inquiried)
            {
                InquiryResult inquiry = (InquiryResult)this.Owner;
                pici_id = inquiry.doublePiCi;
            }
            else
            {
                BatchInfo batchInfo = (BatchInfo)this.Owner;
                pici_id = batchInfo.doublePiCi;
            }
            lbStatus.Text = "未检测";
            //BatchInfo batchInfo = (BatchInfo)this.Owner;
            //pici_id = batchInfo.doublePiCi;

            //strCon = "server = " + ip + "; user id = " + dbUser + "; password = " + dbPwd + "; database = " + database + "; persist security info = false";
            //conn = new MySqlConnection(strCon);
            //comm = new MySqlCommand();


            conn = new SQLiteConnection("Data Source=./data.db");
            comm = new SQLiteCommand();
            //MessageBox.Show("sqlite");
            conn.Open();
            comm = conn.CreateCommand();
            comm.Connection = conn;
            comm.CommandText = "select * from sample where pici_id = " + pici_id + ";";

            try
            {
                reader = comm.ExecuteReader();

                dt.Load(reader);
                dt.Columns[0].ColumnName = "样本编号";
                dt.Columns[1].ColumnName = "样本号";
                dt.Columns[2].ColumnName = "批次号";
                dt.Columns[3].ColumnName = "窖池号";
                dt.Columns[4].ColumnName = "酸度";
                dt.Columns[5].ColumnName = "机器号";
                dt.Columns[6].ColumnName = "检测时间";
                dt.Columns[7].ColumnName = "样本来源";
                dt.Columns[8].ColumnName = "备注";

                dataGridView1.DataSource = dt;
                dataGridView1.Columns[0].ReadOnly = true;
                dataGridView1.Columns[0].Visible = false;
                dataGridView1.Columns[1].ReadOnly = true;
                dataGridView1.Columns[2].Width = 120;
                dataGridView1.Columns[2].ReadOnly = true;
                dataGridView1.Columns[4].ReadOnly = true;
                dataGridView1.Columns[5].ReadOnly = true;
                dataGridView1.Columns[6].ReadOnly = true;
                this.Width = 870;

                //MessageBox.Show("创建定时器");
//                 dingshi = new Timer();
//                 dingshi.Tick +=new EventHandler(dingshi_Tick);
//                 dingshi.Interval = Global.sleepTime;
//                 dingshi.Start();
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("数据库读取错误(TA)：" + ex.Message);
            }
            finally
            {
                reader.Close();
                //conn.Close();
            }
        }

        private void dingshi_Tick(object source, EventArgs e)
        {
            fs = new FileStream(Global.dataExchange, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            readFile = new StreamReader(fs);
            string laiyuan = null;
            if (Global.inquiried)
            {
                InquiryResult batchInfo = (InquiryResult)this.Owner;
                pici_id = batchInfo.doublePiCi;
                laiyuan = batchInfo.dataGridView1[3, batchInfo.doubleRow].Value.ToString();
            }
            else
            {
                BatchInfo batchInfo = (BatchInfo)this.Owner;
                pici_id = batchInfo.doublePiCi;
                laiyuan = batchInfo.dataGridView1[3, batchInfo.doubleRow].Value.ToString();
            }
            while (!readFile.EndOfStream)
            {
                
                //BatchInfo batchInfo = (BatchInfo)this.Owner;
                string line = readFile.ReadLine();
                char[] sp = new char[] { ',' };
                int newYangbenHao = int.Parse(line.Split(sp)[0]);
                float newSuanDu = float.Parse(line.Split(sp)[1]);
                if (isNewRow(newYangbenHao))
                {
                    DataRow dr = dt.NewRow();

                    dr["样本编号"] = ++yangbenbianhao;
                    dr["样本号"] = newYangbenHao;
                    dr["批次号"] = pici_id;
                    dr["窖池号"] = Global.jiaochihao;
                    dr["酸度"] = newSuanDu;
                    dr["机器号"] = Global.getLocalIP();
                    dr["样本来源"] = laiyuan;
                    dr["检测时间"] = string.Format("{0:HH:mm:ss}", DateTime.Now);
                    dr["备注"] = null;
                    //batchinfo.isAddRow = true;
                    //MessageBox.Show("读到值");
                    isRowAdded = true;
                    dt.Rows.Add(dr);
                    
                    rowCount++;
                }
            }
            
        }

        public Boolean isNewRow(int lineNum)
        {
            if ((lineNum - 1) == rowCount)
            {
                return true;
            }
            return false;
        }

        private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            if (isRowAdded)
            {
                isRowAdded = false;

                //MessageBox.Show("添加值的行号" + e.RowIndex.ToString());
                //string pici = dataGridView1[0, e.RowIndex].Value.ToString();
                
                string yangbenhao = (rowCount + 1).ToString();
                string pici_id = Convert.ToString(dataGridView1.Rows[e.RowIndex].Cells["批次号"].Value);
                //string jiaochihao = Convert.ToString(dataGridView1.Rows[e.RowIndex].Cells["窖池号"].Value);
                string jiaochihao = Global.jiaochihao;
                string suandu = Convert.ToString(dataGridView1.Rows[e.RowIndex].Cells["酸度"].Value);
                string jiqihao = Convert.ToString(dataGridView1.Rows[e.RowIndex].Cells["机器号"].Value);
                string shijian = Convert.ToString(dataGridView1.Rows[e.RowIndex].Cells["检测时间"].Value);
                string laiyuan = Convert.ToString(dataGridView1.Rows[e.RowIndex].Cells["样本来源"].Value);
                string beizhu = Convert.ToString(dataGridView1.Rows[e.RowIndex].Cells["备注"].Value);

                comm.CommandText = "insert into sample values(null,'"+yangbenhao+"','" + pici_id + "','" + jiaochihao + "','" + suandu + "','" + jiqihao + "','" + shijian + "','" + laiyuan + "','" + beizhu + "');";
                try
                {
                    comm.ExecuteNonQuery();
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show("数据库插入行错误：" + ex.Message);
                }
            }
        }

        private void 完成检测ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //MessageBox.Show(dataGridView1.RowCount.ToString());
            //BatchInfo batchInfo = (BatchInfo)this.Owner;
            DialogResult result = MessageBox.Show("本批次酸度检测完成？", "检测完成", MessageBoxButtons.YesNo);

            if (result == DialogResult.Yes)
            {
                lbStatus.Text = "检测完成";
                dingshi.Stop();
                finish = true;
                if (Global.inquiried)
                {
                    InquiryResult batchInfo = (InquiryResult)this.Owner;
                    //pici_id = inquiry.doublePiCi;

                    float acidity = 0;
                    for (int i = 0; i < dataGridView1.RowCount; i++)
                    {
                        acidity += float.Parse(dataGridView1[4, i].Value.ToString());
                    }
                    batchInfo.avgAcidity = acidity / dataGridView1.RowCount;
                    batchInfo.avgAcidity = (float)Math.Round(batchInfo.avgAcidity, 3);

                    if (float.IsNaN(batchInfo.avgAcidity))
                    {
                        //非数字
                        MessageBox.Show("结果为非数字，本次测试无效.");
                        return;
                    }

                    MessageBox.Show("本批次平均酸度: " + batchInfo.avgAcidity.ToString());
                    batchInfo.dataGridView1[1, batchInfo.doubleRow].Value = (float)Math.Round(batchInfo.avgAcidity, 3);
                }
                else
                {
                    BatchInfo batchInfo = (BatchInfo)this.Owner;

                    float acidity = 0;
                    for (int i = 0; i < dataGridView1.RowCount; i++)
                    {
                        acidity += float.Parse(dataGridView1[4, i].Value.ToString());
                    }
                    
                    batchInfo.avgAcidity = acidity / dataGridView1.RowCount;
                    batchInfo.avgAcidity = (float)Math.Round(batchInfo.avgAcidity, 3);

                    if (float.IsNaN(batchInfo.avgAcidity))
                    {
                        //非数字
                        MessageBox.Show("结果为非数字，本次测试无效.");
                        return;
                    }

                    MessageBox.Show("本批次平均酸度: " + batchInfo.avgAcidity.ToString());
                    batchInfo.dataGridView1[1, batchInfo.doubleRow].Value = (float)Math.Round(batchInfo.avgAcidity, 3);
                }

                readFile.Close();
                fs.Close();
//                 if (File.Exists(Global.dataExchange))
//                 {
//                     File.Delete(Global.dataExchange);
                //                 }

                if (!control.HasExited)
                {
                    control.Kill();
                }

                System.Threading.Thread.Sleep(2000);
                FileStream file = new FileStream(Global.dataExchange, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read);
                file.SetLength(0);
                file.Close();
                //this.Close();
            }
            else
            {
                //检测未完成
            }
        }

        private void TestAcidity_FormClosing(object sender, FormClosingEventArgs e)
        {
//             if (File.Exists(Global.dataExchange))
//             {
//                 File.Delete(Global.dataExchange);
//             }
            if (qidong)
            {
                if (!finish)
                {
                    MessageBox.Show("检测完成前不可关闭该窗口");
                    e.Cancel = true;
                    return;
                }
            }
        }

        private void 返回批次管理ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
            readFile.Close();
            fs.Close();
        }

        private void 启动检测ToolStripMenuItem_Click(object sender, EventArgs e)
        {
//             if (File.Exists(Global.dataExchange))
//             {
//                 File.Delete(Global.dataExchange);
//             }
            //File.Create(Global.dataExchange);
            control = new Process();
            control.StartInfo.FileName = "ControlTest.exe";
//             control.StartInfo.UseShellExecute = false;
//             control.StartInfo.CreateNoWindow = true;

            dingshi = new Timer();
            dingshi.Tick += new EventHandler(dingshi_Tick);
            dingshi.Interval = Global.sleepTime;
            dingshi.Start();

            control.Start();
            lbStatus.Text = "检测中...";
            qidong = true;
            //MessageBox.Show("执行启动程序");
        }
    }
}
